<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="申请人" size="small">
            <el-input v-model="searchForm.applicant"></el-input>
          </el-form-item>
        </el-col>
        <!--<el-col class="other">-->
          <!--<el-form-item label="团队/部门" size="small">-->
            <!--<el-input v-model="searchForm.teamName"></el-input>-->
          <!--</el-form-item>-->
        <!--</el-col>-->
        <el-col class="professions">
          <el-form-item label="申请车辆" size="small">
            <el-input v-model="searchForm.applicationCar"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col class="datePicker">
          <el-form-item label="时间区间" size="small">
            <el-date-picker type="date" placeholder="选择开始日期" value-format="yyyy-MM-dd" v-model="searchForm.startTimeStr"
            ></el-date-picker>
            <span>-</span>
            <el-date-picker type="date" placeholder="选择结束日期" value-format="yyyy-MM-dd" v-model="searchForm.endTimeStr"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" v-if="isDirector===0" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="650px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
          <el-row>
            <el-col class="dialog-line">
              <el-form-item prop="applicant" label="申请人" size="small">
                <el-autocomplete
                  v-model="teamRow.applicant"
                  :fetch-suggestions="querySearchOperator"
                  @select="handleSelectName"
                  placeholder="请输入内容"
                >
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col class="dialog-line">
              <el-form-item v-if="teamRow.teamName" label="团队/部门" size="small">
                {{teamRow.teamName}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col class="dialog-line">
              <el-form-item prop="applicationTime" label="申请日期" size="small">
                <el-date-picker
                  v-model="teamRow.applicationTime"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择日期"
                  style="width: 190px"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="car" label="申请车辆" size="small" class="item-inline">
                <el-autocomplete
                  v-model="teamRow.car"
                  :fetch-suggestions="querySearchCarInfo"
                  @select="handleSelectCarInfo"
                  placeholder="请输入内容"
                >
                </el-autocomplete>
              </el-form-item>
              <el-form-item prop="address" label="地点" size="small">
                <el-input type="text" v-model="teamRow.address"></el-input>
              </el-form-item>
              <el-form-item label="司机调派需求" size="small">
                <el-radio-group v-model="teamRow.isRequire">
                  <el-radio :label="1">需要</el-radio>
                  <el-radio :label="0">不需要</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="归还油量" size="small">
                <el-input type="number" v-model.number="teamRow.endMl">
                  <span slot="suffix">升</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col class="dialog-line">
              <el-form-item prop="carReason" label="用车事由" size="small">
                <el-input type="text" v-model="teamRow.carReason"></el-input>
              </el-form-item>
              <el-form-item label="里程数" size="small">
                <el-input type="number" v-model.number="teamRow.mileage">
                  <span slot="suffix">KM</span>
                </el-input>
              </el-form-item>
              <el-form-item label="调派司机" size="small">
                <el-input type="text" v-model="teamRow.driverSend"></el-input>
              </el-form-item>
              <el-form-item label="起始油量" size="small">
                <el-input type="number" v-model.number="teamRow.startMl">
                  <span slot="suffix">升</span>
                </el-input>
              </el-form-item>
              <!--<el-form-item prop="actualTime"  label="实际用车时间" size="small">-->
              <!--<el-input type="text" v-model.number="teamRow.actualTime"></el-input>-->
              <!--</el-form-item>-->
            </el-col>
          </el-row>
          <el-form-item label="计划用车时间" size="small">
            <el-date-picker
              v-model="teamRow.planTime"
              type="daterange"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <a target="_blank"
         :href="`/carUseRegistration/export?${encodeURI(exportUrl)}`">
        <el-button type="warning" size="small" icon="el-icon-upload2">
          导出
        </el-button>
      </a>

    </div>
    <my-table
      :data="tableData"
      :col-configs=" isDirector?isDirectorConfigs:colConfigs"
      v-loading="listLoading">
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.registrationId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    addRegistration,
    deleteRegistration,
    getList,
    selectRegistration,
    updateRegistration,
    selectTeam,
    selectOperator,
    selectCarInfo
  } from '@/api/registration'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const applicationTime = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const planTime = {
    props: ['colConfig'],
    filters: {
      formatstart(time) {
        if (time) {
          var date = new Date(parseInt(time.split(',')[0]))
          return formatDate(date, 'yyyy-MM-dd')
        }
      },
      formatend(time) {
        if (time) {
          var date = new Date(parseInt(time.split(',')[1]))
          return formatDate(date, 'yyyy-MM-dd')
        }
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatstart }} - {{ scope.row[colConfig.prop] | formatend }}
      </span>
  </el-table-column>
  `
  }

  const isRequire = function(row, column) {
    return row.isRequire === 1 ? '需要' : '不需要'
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        isDirectorConfigs: [
          { prop: 'applicationTime', label: '申请日期', width: '150', fixed: true, component: applicationTime },
          { prop: 'teamName', label: '团队/部门', width: '150' },
          { prop: 'applicant', label: '申请人', width: '150' },
          { prop: 'carReason', label: '用车事由', width: '150' },
          { prop: 'applicationCar', label: '申请车辆', width: '150' },
          { prop: 'card', label: '车牌', width: '150' },
          { prop: 'planTime', label: '计划用车时间', width: '180', component: planTime }
        ],
        colConfigs: [
          { prop: 'applicationTime', label: '申请日期', width: '150', fixed: true, component: applicationTime },
          { prop: 'teamName', label: '团队/部门', width: '150' },
          { prop: 'applicant', label: '申请人', width: '150' },
          { prop: 'carReason', label: '用车事由', width: '150' },
          { prop: 'applicationCar', label: '申请车辆', width: '150' },
          { prop: 'card', label: '车牌', width: '150' },
          { prop: 'address', label: '地点', width: '150' },
          { prop: 'mileage', label: '里程数(KM)', width: '150' },
          { prop: 'isRequire', label: '司机派遣要求', width: '200', formatter: isRequire },
          { prop: 'driverSend', label: '调派司机', width: '150' },
          { prop: 'planTime', label: '计划用车时间', width: '180', component: planTime },
          { prop: 'startMl', label: '起始油量(升)', width: '150' },
          { prop: 'endMl', label: '归还油量(升)', width: '150' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        professions: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增车辆使用登记',
        dialogType: 0,
        teamRow: {
          planTime: []
        },
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        pca: pca,
        rules: {
          applicationTime: [
            { required: true, message: '请选择申请日期', trigger: 'change' }
          ],
          applicant: [
            { required: true, message: '请输入申请人', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请选择团队/部门', trigger: 'change' }
          ],
          carReason: [
            { required: true, message: '请输入用车事由', trigger: 'change' }
          ],
          car: [
            { required: true, message: '请输入申请车辆', trigger: 'change' }
          ],
          card: [
            { required: true, message: '请输入车牌', trigger: 'change' }
          ],
          address: [
            { required: true, message: '请输入地点', trigger: 'change' }
          ],
          mileage: [
            { required: true, message: '请输入里程数', trigger: 'change' }
          ],
          planTime: [
            { required: true, message: '请输入计划用车时间', trigger: 'change' }
          ],
          actualTime: [
            { required: true, message: '请输入实际用车时间', trigger: 'change' }
          ],
          rate: [
            { required: true, message: '请输入费率', trigger: 'change' }
          ],
          storageTeam: [
            { required: true, message: '请输入入库团队', trigger: 'change' }
          ]
        },
        visible: false,
        exportUrl: '' // 导出参数
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      roleType() {
        return this.$store.state.user.roleType
      },
      isDirector() {
        return this.$store.state.user.isDirector
      },
      teamId() {
        return this.$store.state.user.teamId
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增车辆使用登记'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        this.$set(this.teamRow, 'teamId', this.teamId)
      },
      editTeam(registrationId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改车辆使用登记'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 0
        const params = {
          registrationId: registrationId
        }
        selectRegistration(params).then(response => {
          this.teamRow = response.responseBody
          this.$set(this.teamRow, 'car', this.teamRow.applicationCar + ' ' + this.teamRow.card)
          this.teamRow.planTime = this.teamRow.planTime.split(',')
        })
      },
      submitForm(formName) {
        const params = {
          applicationTime: this.teamRow.applicationTime,
          teamId: this.teamRow.teamId,
          teamName: this.teamRow.teamName,
          applicant: this.teamRow.applicant,
          carReason: this.teamRow.carReason,
          applicationCar: this.teamRow.applicationCar,
          card: this.teamRow.card,
          address: this.teamRow.address,
          mileage: this.teamRow.mileage,
          isRequire: this.teamRow.isRequire,
          driverSend: this.teamRow.driverSend || '',
          startMl: this.teamRow.startMl || 0,
          endMl: this.teamRow.endMl || 0,
          remark: this.teamRow.remark ? this.teamRow.remark : ''
        }
        params.planTime = this.teamRow.planTime ? this.teamRow.planTime.join(',') : ''
        if (!this.dialogType) {
          params.registrationId = this.teamRow.registrationId
        }
        if (this.teamRow.applicationCar) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addRegistration(params).then(response => {
                  this.outerVisible = false
                  this.fetchData()
                })
              } else {
                updateRegistration(params).then(response => {
                  this.outerVisible = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该车辆不存在',
            type: 'warning'
          })
        }
      },
      deleteRow(scope) {
        console.log(this.$refs[`popover-${scope.$index}`])
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          registrationId: scope.row.registrationId,
          isDel: 1
        }
        deleteRegistration(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            name: queryString
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              if (i.tertiarySector) {
                i.teamName = i.tertiarySector
              } else {
                let obj = {}
                obj = global.secondarySectorList.find((items) => {
                  return items.value === i.secondarySector // 筛选出匹配数据
                })
                i.teamName = obj.label
              }
              i.value = i.teamName + ' ' + i.name
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectName(item) {
        this.$set(this.teamRow, 'applicant', item.name)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      querySearchCarInfo(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.applicationCar
        if (queryString) {
          const params = {
            carName: queryString
          }
          selectCarInfo(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.carName + ' ' + i.carBrand
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectCarInfo(item) {
        console.log(item)
        this.$set(this.teamRow, 'applicationCar', item.carName)
        this.$set(this.teamRow, 'card', item.carBrand)
      }
    },
    mounted() {
    },
    watch: {
      'searchForm': {
        handler(newValue, oldValue) {
          let exportUrl = ''
          Object.keys(this.searchForm).map((key) => {
            exportUrl += key + '=' + this.searchForm[key] + '&'
          })
          this.exportUrl = exportUrl
        },
        immediate: true,
        deep: true // 深度监听
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
